"""
NoneBot2 修仙游戏插件
基于大地图的修仙游戏机器人插件
"""
from nonebot import on_command, on_message
from nonebot.adapters import Message
from nonebot.adapters.onebot.v11 import Bot, Event, MessageEvent, GroupMessageEvent, PrivateMessageEvent
from nonebot.params import CommandArg, ArgStr
from nonebot.plugin import PluginMetadata
from nonebot.rule import to_me, Rule
import os
from pathlib import Path

from .game_core import GameCore
from .map_system import MapSystem
from .player_system import PlayerSystem

# 插件元数据
__plugin_meta__ = PluginMetadata(
    name="修仙游戏",
    description="基于大地图的修仙游戏",
    usage="""
修仙游戏指令：
/修仙 - 查看个人信息
/探索 - 探索当前区域
/移动 <区域名> - 移动到指定区域
/地图 - 查看地图信息
/背包 - 查看背包
/使用 <物品名> - 使用物品
/突破 - 尝试突破境界
/休息 - 休息恢复
/区域信息 [区域名] - 查看区域详细信息
/境界信息 - 查看境界一览
""",
    type="application",
    homepage="https://github.com/your-repo/nb-xiuxian",
    supported_adapters={"~onebot.v11"},
)

# 初始化游戏核心
plugin_dir = Path(__file__).parent
game_core = GameCore(plugin_dir)
map_system = MapSystem(game_core)
player_system = PlayerSystem(game_core)

# 加载玩家数据
game_core.load_player_data()

# 角色存在规则：只有已有角色的用户才能触发除“呼叫大运”外的指令
async def _has_role_rule(event: MessageEvent) -> bool:
    user_id = str(event.user_id)
    return game_core.has_player(user_id)

role_required = Rule(_has_role_rule)

# 命令处理器
xiuxian_status = on_command("修仙", aliases={"个人信息", "状态"}, priority=10, block=True, rule=role_required)
explore = on_command("探索", priority=10, block=True, rule=role_required)
move = on_command("移动", aliases={"前往"}, priority=10, block=True, rule=role_required)
map_info = on_command("地图", aliases={"地图信息"}, priority=10, block=True, rule=role_required)
inventory = on_command("背包", aliases={"物品", "道具"}, priority=10, block=True, rule=role_required)
use_item = on_command("使用", priority=10, block=True, rule=role_required)
breakthrough = on_command("突破", priority=10, block=True, rule=role_required)
rest = on_command("休息", aliases={"恢复"}, priority=10, block=True, rule=role_required)
area_info = on_command("区域信息", aliases={"区域"}, priority=10, block=True, rule=role_required)
realm_info = on_command("境界信息", aliases={"境界"}, priority=10, block=True, rule=role_required)

# 新增指令：呼叫大运（为当前用户创建角色）
summon_luck = on_command("呼叫大运", priority=10, block=True)

def get_user_info(event: MessageEvent) -> tuple[str, str]:
    """获取用户信息"""
    user_id = str(event.user_id)
    if hasattr(event, 'sender') and event.sender:
        user_name = event.sender.nickname or event.sender.card or f"修仙者{user_id[-4:]}"
    else:
        user_name = f"修仙者{user_id[-4:]}"
    return user_id, user_name

@xiuxian_status.handle()
async def handle_status(bot: Bot, event: MessageEvent):
    """处理查看个人信息"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    status_info = player_system.get_player_status(player)
    await xiuxian_status.finish(status_info)

@explore.handle()
async def handle_explore(bot: Bot, event: MessageEvent):
    """处理探索"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    result = map_system.explore_area(player)
    game_core.save_player_data()
    
    await explore.finish(result)

@move.handle()
async def handle_move(bot: Bot, event: MessageEvent, args: Message = CommandArg()):
    """处理移动"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    target_area = args.extract_plain_text().strip()
    if not target_area:
        # 显示可前往的区域
        available_areas = map_system.get_available_areas(player)
        if available_areas:
            areas_text = "、".join(available_areas)
            await move.finish(f"请指定要前往的区域。\n可前往的区域：{areas_text}")
        else:
            await move.finish("当前没有可前往的区域")
        return
    
    success, message = map_system.move_to_area(player, target_area)
    if success:
        game_core.save_player_data()
    
    await move.finish(message)

@map_info.handle()
async def handle_map(bot: Bot, event: MessageEvent):
    """处理地图信息"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    map_overview = map_system.get_map_overview(player)
    await map_info.finish(map_overview)

@inventory.handle()
async def handle_inventory(bot: Bot, event: MessageEvent):
    """处理背包信息"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    inventory_info = player_system.get_inventory_info(player)
    await inventory.finish(inventory_info)

@use_item.handle()
async def handle_use_item(bot: Bot, event: MessageEvent, args: Message = CommandArg()):
    """处理使用物品"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    item_name = args.extract_plain_text().strip()
    if not item_name:
        await use_item.finish("请指定要使用的物品名称")
        return
    
    success, message = player_system.use_item(player, item_name)
    if success:
        game_core.save_player_data()
    
    await use_item.finish(message)

@breakthrough.handle()
async def handle_breakthrough(bot: Bot, event: MessageEvent):
    """处理突破境界"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    success, message = player_system.try_breakthrough(player)
    if success:
        game_core.save_player_data()
    
    await breakthrough.finish(message)

@rest.handle()
async def handle_rest(bot: Bot, event: MessageEvent):
    """处理休息"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    result = player_system.rest(player)
    game_core.save_player_data()
    
    await rest.finish(result)

@area_info.handle()
async def handle_area_info(bot: Bot, event: MessageEvent, args: Message = CommandArg()):
    """处理区域信息"""
    user_id, user_name = get_user_info(event)
    player = game_core.get_player(user_id, user_name)
    
    area_name = args.extract_plain_text().strip()
    if not area_name:
        area_name = None  # 默认显示当前区域
    
    area_info_text = map_system.get_area_info(player, area_name)
    await area_info.finish(area_info_text)

@realm_info.handle()
async def handle_realm_info(bot: Bot, event: MessageEvent):
    """处理境界信息"""
    realm_info_text = player_system.get_realm_info()
    await realm_info.finish(realm_info_text)

@summon_luck.handle()
async def handle_summon_luck(bot: Bot, event: MessageEvent):
    """处理呼叫大运：创建角色并提示进入修仙世界"""
    user_id, user_name = get_user_info(event)
    if game_core.has_player(user_id):
        # 已有角色时不重复创建，提示已在修仙世界
        await summon_luck.finish("你已在修仙世界修行，大运持续眷顾你。")
        return
    # 创建角色
    _ = game_core.get_player(user_id, user_name)
    game_core.save_player_data()
    await summon_luck.finish("大运把你送到了一个修仙世界")

# 定期保存数据（可选）
from nonebot import get_driver
driver = get_driver()

@driver.on_shutdown
async def save_on_shutdown():
    """关闭时保存数据"""
    game_core.save_player_data()